require("Prop")

Key = class("Key", Prop)

---

function Key:initialize(relatedDoor)
	
	Prop.initialize(self, relatedDoor, "Key")

	self.relatedDoor = relatedDoor
end  

---

function Key:isAccessibleFrom(location, onlyUseCollapsedKeys, recursiveCall)

	gLogger:log("Check if Key " .. self.name .. " is accessible from : " .. location.name)
	
	local isAccesible = false


	-- prevent recursivity loops
	
	if not recursiveCall then
	
		gLogger:log("Clear recursivity loop prevention for Key : " .. self.name)
		
		self.alreadyVisitedLocations = {}
	end
	
	if not self.alreadyVisitedLocations[location] then
	
		self.alreadyVisitedLocations[location] = true
		
		
		-- check the location
		
		if 
			(
				onlyUseCollapsedKeys and 
				self:isIn(location)
			) or 
			(
				(not onlyUseCollapsedKeys) and 
				self:isPotentialyIn(location)
			)
		then
			gLogger:log("Key " .. self.name .. " is (potentialy) inside : " .. location.name)
			
			isAccesible = true
		else
		
			-- check connected locations
			
			for doorName, door in pairs(location:getDoors()) do

				gLogger:log("Check connected location throught Door : " .. doorName)
			
				if 
					(
						door:isEnabled() or								-- we consider closed non yet collapsed doors with a lock
						door:isOpenableFromThisSide(location, onlyUseCollapsedKeys, true)
					) and
					self:isAccessibleFrom(door:getOtherSide(location), onlyUseCollapsedKeys, true) 
				then			
					gLogger:log("Connected location give acess to key " .. self.name .. " throught Door : " .. doorName)
					
					isAccesible = true
					break
				end
			end
		end 
	end
		
	if not recursiveCall then
	
		self.alreadyVisitedLocations = nil
	end
	
	if isAccesible then
	
		gLogger:log("Key " .. self.name .. " is accesssible from this Location : " .. location.name)
	else
		gLogger:log("Key " .. self.name .. " is not accesssible from this Location : " .. location.name)
	end
		
	return isAccesible
end